<template>
  <div class="user-container" p-30px>
    <el-form :inline="true" :model="formQuery" ref="queryFormRef">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formQuery.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formQuery.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="状态" prop="status" w-200px>
        <el-select v-model="formQuery.status" placeholder="状态">
          <el-option
            v-for="item in options"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSumbitQuery">查询</el-button>
        <el-button type="default" @click="handleResetFeilds">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="user-list">
      <el-button type="primary" plain @click="handleAddUser"
        >添加用户</el-button
      >
      <el-table :data="users" max-height="400">
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :formatter="item.formatter"
        ></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="small"
              link
              @click="handleEditUser(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              link
              @click="handleDeleteUser(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="user-pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          :total="total"
          :page-sizes="[1, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, prev, pager, next"
        ></el-pagination>
      </div>
    </div>
  </div>
  <right-panel v-model="panelVisible" :title="panelTitle" :size="330">
    <editor-user :type="editType" :data="editData" @submit="handleSubmitUser" />
  </right-panel>
</template>

<script setup lang="ts">
import { IUserQuery, Profile } from "@/api/user"
import { useRoleStore } from "@/stores/role"
import { IProfileQuery, useUserStore } from "@/stores/user"
import type { FormInstance } from "element-plus"
const store = useUserStore()
const users = computed(() => store.state.users)
const pageNum = ref(0)
const pageSize = ref(10)
const columns = [
  { prop: "username", label: "用户名" },
  { prop: "mobile", label: "手机" },
  { prop: "email", label: "邮箱" },
  {
    prop: "status",
    label: "状态",
    formatter: (row: Profile) => (row.status ? "启用" : "禁用")
  },
  { prop: "createdAt", label: "创建时间" }
]
const options = [
  { label: "全部", value: "all" },
  { label: "禁用", value: "0" },
  { label: "正常", value: "1" }
]
const formQuery = reactive({
  username: "",
  status: "all",
  mobile: ""
})
const editData = ref<Profile | undefined>(undefined)
const panelVisible = ref(false)
const editType = ref(1) // 0编辑 1新增
const panelTitle = computed(() =>
  editType.value === 1 ? "新增用户" : "编辑用户"
)
const storeRole = useRoleStore()
storeRole.getRoles({
  pageNum: pageNum.value,
  pageSize: pageSize.value
})
const roles = computed(() => storeRole.state.roles)
const addNewUser = (data: Profile) => {
  store.addUser({
    ...data,
    pageSize: pageSize.value,
    pageNum: pageNum.value
  })
  ;(queryFormRef.value as FormInstance).resetFields()
  proxy?.$message.success("用户添加成功")
  panelVisible.value = false
}

const handleAddUser = () => {
  editType.value = 1
  editData.value = {} as Profile
  editData.value.roles = roles.value
  editData.value.roleIds = []
  panelVisible.value = true
}
const getUserList = () => {
  store.getAllUsers({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...formQuery
  } as unknown as IUserQuery)
}
const handleSumbitQuery = () => {
  getUserList()
}
const queryFormRef = useTemplateRef<FormInstance | null>("queryFormRef")
const handleResetFeilds = () => {
  ;(queryFormRef.value as FormInstance).resetFields()
  getUserList()
}
onMounted(() => {
  getUserList()
})
const { proxy } = getCurrentInstance()!
const handleDeleteUser = async (index: number, row: Profile) => {
  try {
    await proxy?.$confirm(`您确认要删除用户${row.username}吗？`, "确认删除", {
      type: "warning"
    })
    await store.removeUser({
      id: row.id,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    } as IProfileQuery)
    proxy?.$message.success("用户删除成功")
  } catch {
    proxy?.$message({
      type: "info",
      message: "已取消删除"
    })
  }
}
const editUser = async (data: IProfileQuery) => {
  store.editUser({
    ...data,
    pageSize: pageSize.value,
    pageNum: pageNum.value
  })
  ;(queryFormRef.value as FormInstance).resetFields()
  proxy?.$message.success("用户编辑成功")
  panelVisible.value = false
}
const handleSubmitUser = (data: Profile) => {
  if (editType.value === 1) {
    addNewUser(data)
  } else {
    editUser(data)
  }
}
const handleEditUser = (index: number, row: Profile) => {
  editType.value = 0
  editData.value = { ...row }
  editData.value.roleIds = row.roles.map((item) => item.id)
  editData.value.roles = roles.value!
  panelVisible.value = true
}
const total = computed(() => store.state.count)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getUserList()
}
const handleCurrentChange = (val: number) => {
  pageNum.value = val - 1
  getUserList()
}
</script>
